//
//  HMHomeTableViewController.swift
//  01-启动图片的搭建
//
//  Created by 白利兵 on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
let statusNormalCellreuseID = "StatusNormalCell"
let statusRetweetedCellreuseID = "statusRetweetedCell"
class HMHomeTableViewController: HMVistorViewController {
    // 定义可重用标示符
    // 懒加载数据列表模型
    private lazy var listViewModel = StatusListViewModel()
     override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
    }
    // 懒加载转场动画的代理控制器
    private lazy var pictureBrowserAnimator = PictureBrowserAnimator()
    override func viewDidLoad() {
        super.viewDidLoad()
        // 添加监听图片的点击通知的观察者
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification, object: nil, queue: nil) { [weak self](notify) -> Void in
            // 获取图片数组和当前选中图片的索引
            guard let indexPath = notify.userInfo![WBStatusSelectedPhotoIndexPathKey] as? NSIndexPath else {
                return
            }
            guard let picUrls = notify.userInfo![WBStatusSelectedPhotoURLsKey] as? [NSURL] else {
                return
            }
            guard let cell = notify.object as? PictureAnimatorPresentDelegate else {
                return
            }
            // 创建照片浏览控制器
            let pictureBrowserVC = PictureBrowserController(currentPicIndexPath: indexPath, picUrls: picUrls)
            
            // 设置控制器转场为自定义
            pictureBrowserVC.modalPresentationStyle = UIModalPresentationStyle.Custom
            // 设置转场动画的代理
            pictureBrowserVC.transitioningDelegate = self?.pictureBrowserAnimator
            // 设置转场动画对象的代理
            self?.pictureBrowserAnimator.setDelegateParams(cell, dismissDelegate: pictureBrowserVC, indexPath: indexPath)
            // 跳转到控制器
            self?.presentViewController(pictureBrowserVC, animated: true, completion: nil)
        }
        // 如果没有登录则加载到访客视图
        if !UserAccountViewModel.shareUserAccount.logon {
            vistorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜")
            return
        }
        // 准备tableview数据
        prepareTableView()
        // 加载网络数据
        loadData()
    }
    // MARK: - 移除通知观察者
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    // MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 判断是否为转发微博
        let viewModel = listViewModel.statusList[indexPath.row]
        //print(viewModel.status)
        let cell = tableView.dequeueReusableCellWithIdentifier(viewModel.reuseID, forIndexPath: indexPath) as! StatusCell
        //print(cell.statusViewModel?.status)
        cell.statusViewModel = viewModel
        // 判断是否是最后一条数据，然后刷新
        if indexPath.row == listViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            // 上拉刷新
            pullUpView.startAnimating()
            loadData()
            
        }
        return cell
    }
    // 行高调用方法
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 返回行高
        return listViewModel.statusList[indexPath.row].rowHeight
    }
    // 准备工作
    private func prepareTableView() {
        // 注册可重用Cell
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: statusNormalCellreuseID)
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: statusRetweetedCellreuseID)

        // 指定预估高度
        tableView.estimatedRowHeight = 200
        
        // 自动计算行高 - 需要一个自上而下的布局，指定一个向下得布局
        tableView.rowHeight = 200
        // 设置刷新控件
        // 创建下拉刷新自定义控件
        refreshControl = WBRefreshControl()
        // 添加监听事件
        refreshControl?.addTarget(self, action:"loadData", forControlEvents: UIControlEvents.ValueChanged)
        // 设置上拉控件为footerView
        tableView.tableFooterView = pullUpView
        
}
    // 懒加载下拉刷新提示控件
    private lazy var pullDownTipLabel: UILabel = {
        let label = UILabel(title: "", fontSize: 18, color: UIColor.darkGrayColor())
        label.backgroundColor = UIColor.orangeColor()
        // 设置位置
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
            return label
        }()
    private func showPulldownTip() {
        // 判断是否下拉刷新
        if listViewModel.pullDownCount == 0 {
            print("没有最新数据")
            return
        }
        let count = listViewModel.pullDownCount
        let message = count > 0 ? "刷新到了 \(count) 条微博" : "没有刷新到数据"
        
        let height:CGFloat = 44
        // 状态栏的高度为20，所以要设为-64
        let rect = CGRect(x: 0, y: -64, width: view.bounds.width, height: height)
        
        pullDownTipLabel.text = message
        pullDownTipLabel.frame = rect
        //view.addSubview(pullDownTipLabel)
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.pullDownTipLabel.frame = CGRectOffset(rect, 0, height + 64)
            }) { _ in
                UIView.animateWithDuration(1.0) { self.pullDownTipLabel.frame = rect }
        }
    }
    // 懒加载上拉刷新指示控件
    private lazy var pullUpView: UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        return indicator
        }()
    // MARK - 加载数据
    @objc func loadData() {
    
        // 开始刷新
        refreshControl?.beginRefreshing()
        // 发送网络请求
        listViewModel.loadStatusList(isPullUp: pullUpView.isAnimating()) { (isSuccessed) -> () in
            print("当前线程为：\(NSThread.currentThread())")
            // 停止刷新
            self.refreshControl?.endRefreshing()
            self.pullUpView.stopAnimating()
            if !isSuccessed {
                print("数据加载错误")
                SVProgressHUD.showErrorWithStatus("加载数据错误，请稍后再试")
                return
            }
            else {
                // 显示下拉刷新提示
                self.showPulldownTip()
                // 刷新数据
                self.tableView.reloadData()
            }
        }
    }

}









